<template>
  <div>
    <el-dialog
      title="新增vo"
      :visible.sync="$store.state.user.objServicedelog"
      width="60%"
      append-to-body
      :before-close="handleClose1"
      :close-on-click-modal="false"
    >
      <el-form ref="dialogForm" :model="formData" :rules="rules">
        <el-row :gutter="20">
          <el-button
            type="primary"
            style="margin-left: 45%"
            @click="handleAddTion"
            size="mini"
            >添加引入包</el-button
          >
          <div v-for="(list, index) in formData.import_Models" :key="index">
            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <el-form-item
                  label="引入包："
                  :prop="`import_Models[${index}]`"
                >
                  <div style="position: relative">
                    <el-input
                      v-model.trim="formData.import_Models[index]"
                      clearable
                      placeholder="请输入引入包"
                    />
                    <i
                      class="el-icon-remove"
                      style="
                        font-size: 20px;
                        color: #409eff;
                        cursor: pointer;
                        position: absolute;
                        top: 24px;
                      "
                      @click="handleTionDelete(index)"
                    ></i>
                  </div>
                </el-form-item>
              </div>
            </el-col>
          </div>
          <el-col :span="12">
            <el-form-item
              prop="moduleId"
              label="选择子项目"
              :rules="[
                {
                  required: true,
                  message: '选择子项目',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                v-model="formData.moduleId"
                placeholder="选择子项目"
                @change="handleChildChange"
              >
                <el-option
                  v-for="item in moduleLists"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="packageName"
              label="选择模块"
              :rules="[
                {
                  required: true,
                  message: '请选择模块',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                v-model="formData.packageName"
                placeholder="请选择模块"
              >
                <el-option
                  v-for="item in packageLists"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light" style="margin-right: 5px">
              <el-form-item
                prop="voClassName"
                label="名称"
                :rules="[
                  {
                    required: true,
                    pattern: /^[A-Z]{1}[0-9a-zA-Z]+$/g,
                    message:
                      '请输入名称，第一个字符必须是大写字母，后面的字符如果有必须是字母或数字',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model.trim="formData.voClassName"
                  clearable
                  placeholder="请输入名称，第一个字符必须是字母，后面的字符如果有必须是字母或数字"
                />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="classDesc" label="对象描述">
              <el-input v-model.trim="formData.classDesc" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="extendsClass"
              label="基类"
              :rules="[
                {
                  required: true,
                  pattern: /^[A-Z]{1}[0-9a-zA-Z]+$/g,
                  message:
                    '请输入基类，第一个字符必须是大写字母，后面的字符如果有必须是字母或数字',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model.trim="formData.extendsClass"
                placeholder="请输入基类，第一个字符必须是字母，后面的字符如果有必须是字母或数字"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: center">
          <i
            class="el-icon-circle-plus"
            style="font-size: 20px; color: #409eff; cursor: pointer"
            @click="handleClick"
          ></i>
        </div>
        <div style="max-height: 190px; overflow-y: scroll; padding-right: 22px">
          <el-row
            :gutter="12"
            v-for="(item, index) in formData.properties"
            :key="index"
          >
            <el-col :span="item.type === 'List' ? 5 : 6">
              <div class="grid-content bg-purple">
                <el-form-item label="属性修饰符" required>
                  <el-select v-model="item.accessModifier">
                    <el-option
                      v-for="item in accessListsModifier"
                      :key="item.label"
                      :label="item.label"
                      :value="item.label"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="item.type === 'List' ? 5 : 6">
              <div class="grid-content bg-purple-light">
                <el-form-item
                  label="属性类型"
                  :prop="`properties.${index}._type_`"
                  :rules="commonRules(leixingLists)"
                >
                  <myElAutocomplete
                    :form="item"
                    attributeName="_type_"
                    :seleteLists="leixingLists"
                    @inputEvent="(val) => handleReturnType(val, item)"
                    valuekey="Label_Desc"
                    placeholder="请选择属性类型"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="4" v-if="item.type === 'List'">
              <div class="grid-content bg-purple-light">
                <el-form-item
                  label="集合元素类型："
                  :prop="`properties.${index}.element_Type`"
                  :rules="commonRules(elementLists)"
                >
                  <myElAutocomplete
                    :form="item"
                    attributeName="element_Type"
                    :seleteLists="elementLists"
                    @inputEvent="(val) => handleReturnElement(val, item)"
                    valuekey="Label_Desc"
                    placeholder="请选择集合元素类型"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="item.type === 'List' ? 5 : 6">
              <div class="grid-content bg-purple-light">
                <el-form-item
                  label="属性名"
                  :prop="`properties.${index}.name`"
                  :rules="rules.name"
                >
                  <el-input
                    v-model.trim="item.name"
                    clearable
                    @input="
                      (value) =>
                        (item.name =
                          value[0].replace(/[^a-zA-Z]/g, '') +
                          value.slice(1).replace(/[^0-9a-zA-Z]/g, ''))
                    "
                    placeholder="请输入属性名，第一个字符必须是字母，后面的字符如果有必须是字母或数字"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="item.type === 'List' ? 5 : 6">
              <div class="grid-content bg-purple-light">
                <el-form-item
                  label="备注"
                  :prop="`properties.${index}.chName`"
                  :rules="rules.chName"
                >
                  <div style="position: relative">
                    <el-input v-model.trim="item.chName" clearable />
                    <i
                      class="el-icon-remove"
                      style="
                        font-size: 20px;
                        color: #409eff;
                        cursor: pointer;
                        position: absolute;
                        top: 24px;
                      "
                      @click="handleDelete(index)"
                    ></i>
                  </div>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  handleSaveSure,
  voClassNameExist,
  listModulePackage,
  findCanUseVo,
  projectdatebaseLists,
  projectManageprojectModellist,
} from "@/api/lowcode";
import myElAutocomplete from "../commonComponents/myElAutocomplete.vue";
export default {
  components: { myElAutocomplete },
  inject: ["SourceCodeTreeList", "moduleModetTreeList", "btnName"],
  data() {
    return {
      accessListsModifier: [
        {
          label: "public",
        },
        {
          label: "protected",
        },
      ],
      rules: {
        voClassName: [
          {
            required: true,
            message:
              "请输入名称，第一个字符必须是字母，后面的字符如果有必须是字母或数字",
            trigger: "blur",
          },
        ],
        type: [{ required: true, message: "请输入属性类型", trigger: "blur" }],
        name: [
          {
            required: true,
            message:
              "请输入属性名，第一个字符必须是字母，后面的字符如果有必须是字母或数字",
            trigger: "blur",
          },
        ],
        chName: [{ required: true, message: "请输入备注", trigger: "blur" }],
        classDesc: [
          { required: true, message: "请输入对象描述", trigger: "blur" },
        ],
      },
      formData: {
        packageName: "",
        moduleId: "",
        import_Models: [""],
        voClassName: undefined,
        classDesc: "",
        properties: [
          {
            accessModifier: "public",
            name: "",
            type: "String",
            _type_: "String | 字符串",
          },
        ],
      },
      radioLists: [
        {
          serviceChName: "登录服务",
          classId: 2,
        },
        {
          serviceChName: "通知服务",
          classId: 3,
        },
      ],
      indexLanlists: [
        {
          code: 1,
          label: "get",
        },
        {
          code: 2,
          label: "post",
        },
      ],
      packageLists: [],
      leixingLists: [],
      elementLists: [],
      moduleLists: [],
    };
  },
  async created() {
    this.findAllCanUseVo();
    await this.projectManageprojectModellist();
    this.formData.moduleId = this.moduleLists[0]?.id;
    this.listModulePackage();
  },
  methods: {
    handleChildChange() {
      this.formData.packageName = "";
      this.listModulePackage();
    },
    async projectManageprojectModellist() {
      this.moduleLists = [];
      const res = await projectManageprojectModellist(
        +sessionStorage.getItem("developLowCodeId")
      );
      if (res?.code === 200) {
        this.moduleLists = res.data;
      }
    },
    handleReturnType(value, item) {
      if (value === "+") {
        this.$store.state.user.objServicedelog = true;
        item._type_ = "";
        item.type = "";
      } else {
        const obj = this.leixingLists.find((item) => item.Label_Desc === value);
        if (obj) {
          item.type = obj.value;
        } else {
          item.type = value;
        }
        if (value === "List | 集合列表") {
          this.$set(
            item,
            "element_Type",
            this.elementLists[0]?.Label_Desc ?? ""
          );
          this.$set(item, "elementType", this.elementLists[0]?.value ?? "");
        } else {
          this.$set(item, "element_Type", "");
          this.$set(item, "elementType", "");
        }
      }
    },
    handleReturnElement(value, item) {
      if (value === "+") {
        this.$store.state.user.objServicedelog = true;
        item.element_Type = "";
        item.elementType = "";
      } else {
        const obj = this.elementLists.find((item) => item.Label_Desc === value);
        if (obj) {
          item.elementType = obj.value;
        } else {
          item.elementType = value;
        }
      }
    },
    async findAllCanUseVo() {
      this.leixingLists = [];
      let res = await findCanUseVo(+sessionStorage.getItem("developLowCodeId"));
      if (res?.code === 200) {
        const lists = res.data.map((item) => {
          return {
            value: item.className,
            label: item.classDesc
              ? `${item.className} | ${item.classDesc}`
              : item.className,
            Label_Desc: item.classDesc
              ? `${item.className} | ${item.classDesc}`
              : item.className,
          };
        });
        this.leixingLists = [
          {
            value: "String",
            label: "String | 字符串",
            Label_Desc: "String | 字符串",
          },
          {
            value: "String[]",
            label: "String[] | 字符串数组",
            Label_Desc: "String[] | 字符串数组",
          },
          {
            value: "int",
            label: "int | 整数",
            Label_Desc: "int | 整数",
          },
          {
            value: "int[]",
            label: "int[] | 整数数组",
            Label_Desc: "int[] | 整数数组",
          },
          {
            value: "boolean",
            label: "boolean | 布尔",
            Label_Desc: "boolean | 布尔",
          },
          {
            value: "List",
            label: "List | 集合列表",
            Label_Desc: "List | 集合列表",
          },
          {
            value: "Map",
            label: "Map | 键值对集合",
            Label_Desc: "Map | 键值对集合",
          },
          {
            value: "long",
            label: "long | 长整型",
            Label_Desc: "long | 长整型",
          },
          {
            value: "double",
            label: "double | 双精度浮点数",
            Label_Desc: "double | 双精度浮点数",
          },
          {
            value: "float",
            label: "float | 浮点数",
            Label_Desc: "float | 浮点数",
          },
          ...lists,
        ];
        const parmesLists = [
          {
            value: "String",
            label: "String | 字符串",
            Label_Desc: "String | 字符串",
          },
          {
            value: "Boolean",
            label: "Boolean | 布尔",
            Label_Desc: "Boolean | 布尔",
          },
          {
            value: "Integer",
            label: "Integer | 整数",
            Label_Desc: "Integer | 整数",
          },
          ...lists,
        ];
        this.projectdatebaseLists(parmesLists);
      }
    },
    async projectdatebaseLists(parmesLists) {
      this.elementLists = [];
      const res = await projectdatebaseLists(
        +sessionStorage.getItem("developLowCodeId")
      );
      if (res?.code === 200) {
        const lists = res.data.map((item) => ({
          value: item.className,
          label: item.classDesc
            ? `${item.className} | ${item.classDesc}`
            : item.className,
          Label_Desc: item.classDesc
            ? `${item.className} | ${item.classDesc}`
            : item.className,
        }));
        this.elementLists = [...parmesLists, ...lists];
        this.leixingLists = [...this.leixingLists, ...lists];
      }
    },
    async listModulePackage() {
      this.packageLists = [];
      const res = await listModulePackage(
        +sessionStorage.getItem("developLowCodeId"),
        this.formData.moduleId
      );
      if (res?.code === 200) {
        this.packageLists = res.data;
      }
    },
    handleClick() {
      this.formData.properties.push({
        accessModifier: "public",
        name: "",
        type: "String",
        _type_: "String | 字符串",
      });
    },
    handleDelete(index) {
      if (this.formData.properties.length > 1) {
        this.formData.properties.splice(index, 1);
      }
    },
    handleAddTion() {
      this.formData.import_Models.push("");
    },
    handleTionDelete(index) {
      if (this.formData.import_Models.length > 1) {
        this.formData.import_Models.splice(index, 1);
      }
    },
    handleClose1() {
      this.$store.state.user.objServicedelog = false;
    },
    async handleBlur(name, id) {
      const res = await voClassNameExist(name, id);
      if (res?.code === 200) {
        if (res.data) {
          this.$message({
            message: "名称已存在，请从新输入",
            type: "warning",
            showClose: true,
          });
          this.formData.voClassName = "";
          return true;
        }
      }
    },
    handleSave() {
      this.$refs["dialogForm"].validate(async (valid) => {
        if (valid) {
          const flag = await this.handleBlur(
            this.formData.voClassName,
            +sessionStorage.getItem("developLowCodeId")
          );
          if (flag) return;
          const form_Data = JSON.parse(JSON.stringify(this.formData));
          form_Data.importModels = form_Data.import_Models;
          if (
            form_Data.import_Models.length == 1 &&
            form_Data.import_Models[0] == ""
          ) {
            form_Data.importModels = [];
          }
          form_Data.properties.forEach((item) => {
            if (item.type === "List") {
              item.type = `${item.type}<${item.elementType}>`;
            }
          });
          const res = await handleSaveSure(
            form_Data,
            +sessionStorage.getItem("developLowCodeId"),
            form_Data.moduleId
          );
          if (res?.code === 200) {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.$store.state.user.objServicedelog = false;
            if (this.btnName == "显示源码") {
              this.moduleModetTreeList();
            } else if (this.btnName == "显示模块") {
              this.SourceCodeTreeList();
            }
            if (this.$parent.findAllCanUseVo) {
              this.$parent.findAllCanUseVo();
            }
            if (this.$parent.currentComponent === "basicsssssComponents") {
              this.$parent.$refs.basicsssssComponents.$refs.basicComponents.findAllCanUseVo();
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
